package com.JZ.QM.controller;

import com.JZ.QM.common.entity.UserInfoEntity;
import com.JZ.QM.common.utils.CommonResult;
import com.JZ.QM.service.UserInfoService;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lyp
 * @email lyp@gmail.com
 * @date 2020/6/23 14:19
 */
@RefreshScope
@RestController
@Slf4j
@RequestMapping("/management/user")
public class UserController {

    @Resource
    UserInfoService userInfoService;

    @Resource
    StringRedisTemplate stringRedisTemplate;


    /**
     * 发送验证码
     * @param phoneNumber
     * @return
     * @throws ClientException
     */
    @RequestMapping("/sendCode")
    public CommonResult sendCode(String phoneNumber, Integer identification) throws ClientException {
        //是否发送成功
        boolean sendFlag = true;

        //先从缓存中获取该手机号对应的验证码，如果存在则检测发送间隔
        String redisCode = stringRedisTemplate.opsForValue().get("code:"+phoneNumber);

        if(redisCode!=null){
            long time = Long.parseLong(redisCode.split("_")[1]);
            //如果距上次发送验证码不到60秒钟，则不再次发送验证码
            if(System.currentTimeMillis()-time < 60000){
                return CommonResult.error(201,"请60秒后重试");
            }
        }
        //构造验证码
        String code = UUID.randomUUID().toString().substring(0,6);

        //发送验证码
        sendFlag = userInfoService.sendCode(phoneNumber,code,identification);

        log.info(String.valueOf(sendFlag));

        if(sendFlag){
            //设置缓存有效时间 1分钟,验证码上带上系统当前时间，防止页面刷新多次发送
            stringRedisTemplate.opsForValue().set(
                    "code:"+phoneNumber,
                    code+"_"+System.currentTimeMillis(),
                    1,
                    TimeUnit.MINUTES);
            return CommonResult.success();
        }else {
            return CommonResult.error();
        }

    }

    /**
     * 验证账号是否已经存在
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/validateUserAccount")
    public CommonResult validateUserAccount(String phoneNumber){
        //验证账号是否已经存在
        boolean validFlag = userInfoService.validUserAccount(phoneNumber);

        if(validFlag){
            return CommonResult.success("新账号");
        }else {
            return CommonResult.error(201,"已经存在相同的账号");
        }
    }

    /**
     * 用户注册功能
     * @param phoneNumber
     * @param registerCode
     * @return
     */
    @RequestMapping("/register")
    public CommonResult register(String phoneNumber, String registerCode){
        //先从缓存中获取该手机号对应的验证码
        String redisCode = stringRedisTemplate.opsForValue().get("code:"+phoneNumber);
        //注册flag
        boolean saveRegister = true;
        //存储cookie的Map
        Map<String,String> cookieMap = new HashMap<>();

        if(redisCode!=null){
            //缓存中的验证码
            String code = redisCode.split("_")[0];

            if(code.equals(registerCode)){

                saveRegister = userInfoService.register(phoneNumber);

                if(saveRegister){
                    //获取cookie需要的属性
                    cookieMap = userInfoService.getCookie(phoneNumber);
                    //删除缓存
                    stringRedisTemplate.delete("code:"+phoneNumber);

                    return CommonResult.success("注册成功")
                            .put("id",cookieMap.get("id"))
                            .put("nickName",cookieMap.get("nickName"))
                            .put("images",cookieMap.get("images"));
                }else {
                    return CommonResult.error(201,"注册失败");
                }

            }else {
                return CommonResult.error(201,"验证码错误");
            }

        }else{
            return CommonResult.error(202,"验证码已过期");
        }
    }


    /**
     * 用户登录功能
     * @param phoneNumber
     * @param loginCode
     * @return
     */
    @RequestMapping("/login")
    public CommonResult login(String phoneNumber, String loginCode){
        //先从缓存中获取该手机号对应的验证码
        String redisCode = stringRedisTemplate.opsForValue().get("code:"+phoneNumber);
        //存储cookie的Map
        Map<String,String> cookieMap = new HashMap<>();

        if(redisCode!=null){
            //缓存中的验证码
            String code = redisCode.split("_")[0];

            if(code.equals(loginCode)){
                //获取cookie需要的属性
                cookieMap = userInfoService.getCookie(phoneNumber);

                //删除缓存
                stringRedisTemplate.delete("code:"+phoneNumber);

                return CommonResult.success("登录成功")
                        .put("id",cookieMap.get("id"))
                        .put("nickName",cookieMap.get("nickName"))
                        .put("images",cookieMap.get("images"))
                        .put("riskLevel",cookieMap.get("riskLevel"));
            }else {
                return CommonResult.error(201,"验证码错误");
            }
        }else{
            return CommonResult.error(202,"验证码已过期");
        }
    }

    /**
     * 返回用户实体信息
     * @param userId
     * @return
     */
    @RequestMapping("/getUserInfoEntity")
    public CommonResult getUserInfoEntity(Long userId){
        //用户实体
        UserInfoEntity userInfoEntity = new UserInfoEntity();

        userInfoEntity = userInfoService.getById(userId);

        return CommonResult.success().put("userInfoEntity",userInfoEntity);
    }
}
